package com.nageoffer.shortlink.admin.common.biz.user;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.esotericsoftware.minlog.Log;
import com.google.common.collect.Lists;
import com.nageoffer.shortlink.admin.common.convention.exception.ClientException;
import com.nageoffer.shortlink.admin.common.convention.result.Results;
import com.nageoffer.shortlink.admin.common.enums.UserErrorCodeEnum;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.List;
import java.util.Objects;
import static java.nio.charset.StandardCharsets.UTF_8;



/**
 * 用户信息传输过滤器
 *
 */
@RequiredArgsConstructor
public class UserTransmitFilter implements Filter {
    
    private final StringRedisTemplate stringRedisTemplate;

    public static final List<String> IGNORE_URL = Lists.newArrayList(
            "/api/short-link/admin/v1/user/login",
            "/api/short-link/admin/v1/user/has-username"
    );

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String requstUrl =  httpServletRequest.getRequestURI();
        Log.info("拦截器开始执行");
        if (!IGNORE_URL.contains(requstUrl)){
            String method = httpServletRequest.getMethod();
            if (!(Objects.equals(requstUrl,"/api/short-link/admin/v1/user")&&Objects.equals(method,"POST"))){
                String username = httpServletRequest.getHeader("username");
                String token = httpServletRequest.getHeader("token");
                // 检查 username 和 token 是否为 null 或空字符串
                if (!StrUtil.isAllNotBlank(username,token)){
                    returnJson(servletResponse, JSON.toJSONString(Results.failure(new ClientException(UserErrorCodeEnum.USER_TOKEN_FAIL))));
                    return;
                }
                if (StringUtils.hasText(username) && StringUtils.hasText(token)) {
                    Object userInfoJsonStr = null;
                    try{
                        userInfoJsonStr = stringRedisTemplate.opsForHash().get("login_" + username, token);
                    }
                    catch (Exception e){
                        returnJson(servletResponse, JSON.toJSONString(Results.failure(new ClientException(UserErrorCodeEnum.USER_TOKEN_FAIL))));
                        return;

                    }

                    UserInfoDTO userInfoDTO = JSON.parseObject(userInfoJsonStr.toString(), UserInfoDTO.class);
                    UserContext.setUser(userInfoDTO);
                }
            }
        }
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }
    }
    private void returnJson(ServletResponse response, String json) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        try {

            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            Log.error("response error", e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }

}